package com.epam.cdp.jpa.dao;

import java.util.List;

import javax.ejb.Stateful;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.epam.cdp.jpa.model.BookCategory;

@Stateful
public class BookCategoryDAO extends AbstractStatefullDAO<BookCategory> {

    private static final long serialVersionUID = 1L;

    @Override
    public Class<BookCategory> getEntityClass() {
	return BookCategory.class;
    }
    
    public List<BookCategory> getRootCategories() {
	CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
	CriteriaQuery<BookCategory> criteriaQuery = criteriaBuilder.createQuery(BookCategory.class);
	Root<BookCategory> bookCategory = criteriaQuery.from(BookCategory.class);
	
	Predicate noParentPredicate = criteriaBuilder.isNull(bookCategory.get("parent"));
	
	criteriaQuery.select(bookCategory).where(noParentPredicate);
	
	List<BookCategory> resultList = getEntityManager().createQuery(criteriaQuery).getResultList();
	return resultList;
    }
    
    
    /**
     * Method contains specific logic of  deleting tree element.
     */
    @Override
    public void remove(long id) {
        BookCategory todelte = getEntityManager().find(getEntityClass(), id);
        if (todelte.getParent() != null) {
            todelte.getParent().getChildren().remove(todelte);
            todelte.setParent(null);
        }
        super.remove(id);
    }
    
    @Override
    public void remove(BookCategory entity) {
        this.remove(entity.getId());
    }
}
